import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API.replace(/['"]/g, ''), // 移除可能存在的引号
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 0 // 取消请求超时限制
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    const token = getToken()
    if (token) {
      // 添加 JWT token 到请求头
      config.headers['Authorization'] = `Bearer ${token}`
    }

    // 如果是GET请求且有data，将data转换为params
    if (config.method === 'get' && config.data) {
      config.params = config.data
      delete config.data
    }

    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    return res
  },
  error => {
    console.log('err' + error)
    if (error.response) {
      switch (error.response.status) {
        case 401:
          Message({
            message: '登录已过期，请重新登录',
            type: 'error',
            duration: 5 * 1000
          })
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
          break
        case 403:
          Message({
            message: '没有权限访问该资源',
            type: 'error',
            duration: 5 * 1000
          })
          break
        case 404:
          Message({
            message: '请求的资源不存在',
            type: 'error',
            duration: 5 * 1000
          })
          break
        case 500:
          Message({
            message: '服务器错误',
            type: 'error',
            duration: 5 * 1000
          })
          break
        default:
          Message({
            message: error.response.data.message || '请求失败',
            type: 'error',
            duration: 5 * 1000
          })
      }
    } else {
      Message({
        message: error.message || '网络错误',
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
